package com.gitee.wsl.android.ui.ext

//package com.dylanc.longan

import androidx.activity.ComponentActivity
import androidx.annotation.MainThread
import androidx.fragment.app.Fragment
import androidx.lifecycle.*
import androidx.lifecycle.viewmodel.CreationExtras
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlin.coroutines.EmptyCoroutineContext

val applicationViewModelStore by lazy { ViewModelStore() }

@MainThread
inline fun <reified VM : ViewModel> ComponentActivity.applicationViewModels(
    noinline extrasProducer: (() -> CreationExtras) = { defaultViewModelCreationExtras },
    noinline factoryProducer: () -> ViewModelProvider.Factory = { defaultViewModelProviderFactory }
): Lazy<VM> = createApplicationViewModelLazy(extrasProducer,factoryProducer)

@MainThread
inline fun <reified VM : ViewModel> Fragment.applicationViewModels(
    noinline extrasProducer: (() -> CreationExtras) = { defaultViewModelCreationExtras },
    noinline factoryProducer: () -> ViewModelProvider.Factory = { defaultViewModelProviderFactory }
): Lazy<VM> = createApplicationViewModelLazy(extrasProducer,factoryProducer)

@MainThread
inline fun <reified VM : ViewModel> createApplicationViewModelLazy(
    noinline extrasProducer: (() -> CreationExtras),
    noinline factoryProducer: () -> ViewModelProvider.Factory
) = ViewModelLazy(VM::class, { applicationViewModelStore }, factoryProducer,extrasProducer)

fun ViewModel.safeLaunch(context: kotlin.coroutines.CoroutineContext = EmptyCoroutineContext, tryBlock: CoroutineScope.() -> Unit) {
    viewModelScope.launch(context) {
        try {
            tryBlock()
        } catch (e: Throwable) {
            e.printStackTrace()
        }
    }
}

/*//顶层函数版
inline fun <reified T : ViewModel> getViewModel(owner: ViewModelStoreOwner, configLiveData: T.() -> Unit = {}): T =
    ViewModelProvider(owner)[T::class.java].apply { configLiveData() }

//扩展函数版
inline fun <reified T : ViewModel> ViewModelStoreOwner.getSelfViewModel(configLiveData: T.() -> Unit = {}): T =
    getViewModel(this, configLiveData)*/
